﻿using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Database;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System.Runtime.InteropServices;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for SummaryForm.xaml
    /// </summary>
    /// 
    public partial class VKPOS : DocumentBase
    {
        #region-------------Properties-----------------------
        public bool checkVK07 = true;
        public OracleConnection OracleDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        public INTEXDataSet setUI;
        VKPOSData m_Data, m_DataX;
        public DataSet setResult;
        private DataRow dwUI;
        VKPOSReport m_rpt;
        ExcelX.ExcelLib.ExcelAgent m_exAgent;
        DataSet setANINFOR = new DataSet();
        DataTable tableUI;
        DataTable tableVKPOS;
        string UserGroup;
        public ArrayList XEditablelines;
        public TextBox TxtUserID
        {
            get
            {
                return ((TextBox)this.FindName("txtUserID"));
            }
        }
        public VKPOS()
        {
            InitializeComponent();
            this.Name = "销售单";
            this.Title = "销售单";
        }
        public void SetUpEditableList()
        {
            try
            {
                EDIT_TXTKON edittxt;
                List<string> userg = new List<string>();
                userg.Add("EDIT_VK");
                userg.Add("EDIT_TE");
                userg.Add("EDIT_TEM");
                userg.Add("EDIT_EK");
                foreach (string usergroup in userg)
                {
                    edittxt = new EDIT_TXTKON();
                    edittxt.UserGroup = usergroup;
                    switch (usergroup)
                    {
                        case "EDIT_VK":
                            edittxt.EditibleLine.Add("KVKTTXT01");
                            edittxt.EditibleLine.Add("KVKTTXT02");
                            edittxt.EditibleLine.Add("KVKTTXT03");
                            edittxt.EditibleLine.Add("KVKTTXT04");
                            edittxt.EditibleLine.Add("KVKTTXT05");
                            edittxt.EditibleLine.Add("KVKTTXT06");
                            edittxt.EditibleLine.Add("KVKTTXT07");
                            edittxt.EditibleLine.Add("KVKTTXT08");
                            edittxt.EditibleLine.Add("KVKTTXT09");
                            edittxt.EditibleLine.Add("KVKTTXT10");
                            edittxt.EditibleLine.Add("KVKTTXT11");
                            edittxt.EditibleLine.Add("KVKTTXT12");
                            break;
                        case "EDIT_TE":
                            edittxt.EditibleLine.Add("PVKTTXT01");
                            edittxt.EditibleLine.Add("PVKTTXT02");
                            edittxt.EditibleLine.Add("PVKTTXT03");
                            edittxt.EditibleLine.Add("PVKTTXT04");
                            edittxt.EditibleLine.Add("PVKTTXT05");
                            break;
                        case "EDIT_TEM":
                            edittxt.EditibleLine.Add("PVKTTXT06");
                            edittxt.EditibleLine.Add("PVKTTXT07");
                            edittxt.EditibleLine.Add("PVKTTXT08");
                            break;
                        case "EDIT_EK":
                            edittxt.EditibleLine.Add("PVKTTXT09");
                            edittxt.EditibleLine.Add("PVKTTXT10");
                            edittxt.EditibleLine.Add("PVKTTXT11");
                            edittxt.EditibleLine.Add("PVKTTXT12");
                            edittxt.EditibleLine.Add("PVKTTXT13");
                            break;
                        default:
                            break;
                    }
                    XEditablelines.Add(edittxt);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void UpdateEditablelines(string userID, string usergroup)
        {
            try
            {
                var query = from EDIT_TXTKON ext in XEditablelines
                            where ext.UserGroup == usergroup
                            select ext;
                foreach (EDIT_TXTKON ext in query)
                {
                    ext.UserID = userID;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public bool StartEdit(string userID, string usergroup)
        {
            bool flagok = false;
            try
            {
                var query = from EDIT_TXTKON ext in XEditablelines
                            where ext.UserGroup == usergroup
                            select ext;
                foreach (EDIT_TXTKON ext in query)
                {
                    if (ext.UserID == "")
                    {
                        flagok = true;
                        break;
                    }
                    else
                    {
                        if (ext.UserID == userID)
                        {
                            flagok = true;
                        }
                    }
                }

                if (!flagok)
                {
                    MessageBox.Show("注意权限。");
                    return false;
                }

                foreach (EDIT_TXTKON ext in query)
                {
                    foreach (string elename in ext.EditibleLine)
                    {
                        TextBox txtb = this.FindName(elename) as TextBox;
                        if (txtb == null)
                            continue;
                        if (txtb.IsReadOnly == true)
                        {
                            txtb.IsReadOnly = false;
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return true;
        }
        public void EndEdit(string usergroup)
        {
            bool flagok = false;
            try
            {
                var query = from EDIT_TXTKON ext in XEditablelines
                            where ext.UserGroup == usergroup
                            select ext;

                foreach (EDIT_TXTKON ext in query)
                {
                    foreach (string elename in ext.EditibleLine)
                    {
                        TextBox txtb = this.FindName(elename) as TextBox;
                        if (txtb.IsReadOnly == false)
                        {
                            txtb.IsReadOnly = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }
        public TextBox TxtMANDANT
        {
            get
            {
                return this.FindName("txtMANDANT") as TextBox;
            }
        }
        public TextBox TxtKRS
        {
            get
            {
                return this.FindName("txtKRS") as TextBox;
            }
        }
        public TextBox TxtLFD
        {
            get
            {
                return this.FindName("txtLFD") as TextBox;
            }
        }
        #endregion
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                setUI = (INTEXDataSet)TryFindResource("iNTEXDataSet");
                dwUI = tableUI.NewRow();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;

        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            try
            {
                base.SetUp(dicParamater);
                InitializeComponent();
                this.dicParamater = dicParamater;
                OracleDB = (OracleConnection)dicParamater["OracleDB"];
                proxy = (IntexReptServBLClient)dicParamater["proxy"];
                txtUserID.Text = (string)dicParamater["User"];
                char[] passwordChars = ((string)dicParamater["Pwd"]).ToCharArray(); 
                foreach (char c in passwordChars)
                {
                    //txtPassword.SecurePassword.AppendChar(c);
                    
                }
                txtPassword.Password = (string)dicParamater["Pwd"];
                orlReadCommand = OracleDB.CreateCommand();
                orlReadCommand.Parameters.Add("OrdNum", OracleType.NVarChar).Value = "";

                m_Data = new VKPOSData(OracleDB,proxy, (string)dicParamater["User"]);
                m_Data.checkVK07 = checkVK07;
                tableUI = new DataTable("UIData");
                tableUI.Columns.Add("VKKMANDANT", typeof(string));
                tableUI.Columns.Add("VKKAUFKRS", typeof(string));
                tableUI.Columns.Add("VKKAUFLFD", typeof(string));
                tableUI.Columns.Add("VKPNEUDAT", typeof(string));
                
                /*txtKRS.Text = "C1";
                txtLFD.Text = "63001";
                txtUserID.Text = "SUNLV";*/
                DateTime dtnow = DateTime.Now;
                txtDATE.Text = dtnow.Year.ToString() + m_Data.Right("00"+ dtnow.Month.ToString(),2) +m_Data.Right("00"+dtnow.Day.ToString(),2);
                XEditablelines = new ArrayList();
                SetUpEditableList();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                setUI.Tables.Clear();
                setUI.AcceptChanges();
                if (dwUI == null)
                {
                    dwUI = tableUI.NewRow();
                }
                m_Data.checkVK07 = checkVK07;
                string VKKMANDANT = txtMANDANT.Text.ToString();
                string VKKAUFKRS = txtKRS.Text.ToString();
                string VKKAUFLFD = m_Data.Right("000000" + txtLFD.Text.ToString(), 6);
                dwUI["VKKMANDANT"] = VKKMANDANT;
                dwUI["VKKAUFKRS"] = VKKAUFKRS;
                dwUI["VKKAUFLFD"] = VKKAUFLFD; 
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    setResult = m_Data.GetData(dwUI);
                }
                setUI.Merge(setResult);
                string user;
                foreach (DataRow dwVKPOS in setUI.Tables["VKPOS"].Rows)
                {
                    user = dwVKPOS["KVKTTXT31"].ToString().Trim();
                    if (user != "")
                    {
                        user = m_Data.Left(dwVKPOS["KVKTTXT31"].ToString().Trim() + "        ", 8);
                        UpdateEditablelines(user, "EDIT_VK");
                    }
                    user = dwVKPOS["PVKTTXT31"].ToString().Trim();
                    if (user != "")
                    {
                        user = m_Data.Left(dwVKPOS["PVKTTXT31"].ToString().Trim() + "        ", 8);
                        UpdateEditablelines(user, "EDIT_TE");
                    }
                    user = dwVKPOS["PVKTTXT32"].ToString().Trim();
                    if (user != "")
                    {
                        user = m_Data.Left(dwVKPOS["PVKTTXT32"].ToString().Trim() + "        ", 8);
                        UpdateEditablelines(user, "EDIT_TEM");
                    }
                    user = dwVKPOS["PVKTTXT33"].ToString().Trim();
                    if (user != "")
                    {
                        user = m_Data.Left(dwVKPOS["PVKTTXT33"].ToString().Trim() + "        ", 8);
                        UpdateEditablelines(user, "EDIT_EK");
                    }
                }
                dgVKKOPF.DataContext = setUI.Tables["VKKOPF"];
                dgVKPOS.DataContext = setUI.Tables["VKPOS"];
                if (!checkVK07)
                    return;
                m_Data.UpdateTXTKON(setUI.Tables["VKPOS"],m_Data.UserID, "ALL");
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
   
        private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                string usergroup = btn.Tag as string;
                if (btn.Content == "保存")
                {
                    m_Data.UserGroup = UserGroup;
                    m_Data.UpdateTXTKON(setUI.Tables["VKPOS"],m_Data.UserID,UserGroup);
                    EndEdit(UserGroup);
                    btn.Content = "编辑";
                    btnQuery_Click(null, null);
                    return;
                }
                UserGroup = usergroup;
                if (StartEdit(m_Data.UserID, UserGroup))
                {
                    btn.Content = "保存";
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            string PrintType = "DirectPrint";
            GenerateReport(PrintType);
        }
        private void btnPrintPreview_Click(object sender, RoutedEventArgs e)
        {
            string PrintType = "OpenExcel";
            GenerateReport(PrintType);
        }
        public void GenerateReport(string PrintType)
        {
            Process[] AllProcesses = Process.GetProcessesByName("EXCEL");

            // check to kill the right process
            foreach (Process ExcelProcess in AllProcesses)
            {
                ExcelProcess.Kill();
            }
            using (new LongOperation(this, "读取符合条件的记录"))
            {
                m_DataX = new VKPOSData(dicParamater);
                m_DataX.exAgent._app.Visible = false;
                m_DataX.OracleDB = this.OracleDB;
                m_DataX.proxy = this.proxy;
                m_rpt = new VKPOSReport(dicParamater);
                m_rpt.dsSource = setUI;
                m_rpt.PrintType = PrintType;
                m_rpt.exAgent = m_DataX.exAgent;
                m_rpt.WriteExcelReport("EXCEL");
            }
        }
        void txt_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox tb = sender as TextBox;
            //tb.Text = "";
        }
        private void btnRegenerateLastInv_Click(object sender, RoutedEventArgs e)
        {
            btnQuery_Click(null, null);
        }
        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView;
                    txtKRS.Text = drv.Row["VKPAUFKRS"].ToString();
                    txtLFD.Text = drv.Row["VKPAUFLFD"].ToString();
                    txtKRS.Focus();
                    txtLFD.Focus();
                    txtKRS.Focus();
                    btnQuery_Click(null, null);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnLogIn_Click(object sender, RoutedEventArgs e)
        {
            string Mandant = txtMANDANT.Text.ToUpper();
            string userID =m_Data.Left( txtUserID.Text.ToUpper()+"        ",8);
            System.Security.SecureString sPassword = this.txtPassword.SecurePassword; 

            DataSet setResult = m_Data.LogIn(Mandant, userID, sPassword);
            if (setResult.Tables.Count > 0)
            {
                if (setResult.Tables[0].Rows.Count == 0)
                    return;
                DataRow dwUser = setResult.Tables[0].Rows[0];
                txtSPRACHKZ.Text = dwUser["HRSPRKZ"].ToString();
                btnQuery.IsEnabled = true;
                btnLogIn.Content = dwUser["HRVNAME"].ToString().Trim() + dwUser["HRNNAME"].ToString().Trim();
                m_Data.UserID = userID;
                m_Data.MANDANT = Mandant;
                m_Data.SPRACHKZ = txtSPRACHKZ.Text.Trim();
                dwUI = tableUI.NewRow();
                dwUI["VKPNEUDAT"] = txtDATE.Text.ToString().Trim();
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    setResult = m_Data.ListVKPOS(dwUI);
                }
                dgEDIT_TD.DataContext = setResult.Tables["EDIT_TD"];
                dgEDIT_VK.DataContext = setResult.Tables["EDIT_VK"];
                dgEDIT_TE.DataContext = setResult.Tables["EDIT_TE"];
                dgEDIT_TEM.DataContext = setResult.Tables["EDIT_TEM"];
                dgEDIT_EK.DataContext = setResult.Tables["EDIT_EK"];

            }
        }
        private void Grid_PreviewKeyDown(object sender, KeyEventArgs e) 
        { 
            var uie = e.OriginalSource as UIElement; 
            if (e.Key == Key.Enter)
            {
                e.Handled = true; 
                uie.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); 
            } 
        }
        private void dgVKKOPF_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                dwUI = tableUI.NewRow();
                dwUI["VKPNEUDAT"] = txtDATE.Text.ToString().Trim();
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    setResult = m_Data.ListVKPOS(dwUI);
                }
                dgEDIT_TD.DataContext = setResult.Tables["EDIT_TD"];
                dgEDIT_VK.DataContext = setResult.Tables["EDIT_VK"];
                dgEDIT_TE.DataContext = setResult.Tables["EDIT_TE"];
                dgEDIT_TEM.DataContext = setResult.Tables["EDIT_TEM"];
                dgEDIT_EK.DataContext = setResult.Tables["EDIT_EK"];
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }
    }
}
